package com.edais.service.imp;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.edais.dao.CouponsLuckDrawDao;
import com.edais.dao.LuckDrawDao;
import com.edais.dao.RateRisesCouponsDao;
import com.edais.dao.ShopVouchersDao;
import com.edais.dao.SystemSettingDao;
import com.edais.dao.UserDao;
import com.edais.dao.UserVouchersDao;
import com.edais.domain.CouponsLuckDraw;
import com.edais.domain.RateRisesCoupons;
import com.edais.domain.ShopVouchers;
import com.edais.domain.UserVouchers;
import com.edais.domain.VouchersRule;
import com.edais.service.ActivityService;
import com.edais.service.LuckDrawService;
import com.edais.service.PointService;
import com.edais.service.gift.GiftPackageService;
import com.edais.util.Consts;
import com.edais.util.Message;
import com.edais.util.StringUtil;
import com.edais.vo.LuckDraw;

@Service

@Transactional
public class LuckDrawServiceImpl implements LuckDrawService {

	private static final Log logger = LogFactory
			.getLog(LuckDrawServiceImpl.class);

	@Autowired
	private UserDao usersDao;

	@Autowired
	private CouponsLuckDrawDao couponsLuckDrawDao;
	
	@Autowired
	private RateRisesCouponsDao rateRisesCouponsDao;
	
	@Autowired
	private LuckDrawDao luckDrawDao;
	
	@Autowired
	private UserVouchersDao userVouchersDao;
	
	@Autowired
	private ShopVouchersDao shopVouchersDao;
	
	@Autowired
	private SystemSettingDao systemSettingDao;

	@Autowired
	private PointService pointService;
	
	@Autowired
	private GiftPackageService giftPackageService;
	
	@Autowired
	private ActivityService activityService;

	@Override
	public Map<String, Object> queryLuckDrawList(Map<String, Object> paramsMap)  throws Exception{
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		//查询抽奖设置信息
		CouponsLuckDraw couponsLuckDraw = couponsLuckDrawDao.queryCouponsLuckDrawByUserId(paramsMap);
		String activityDesc = "";
//		if (couponsLuckDraw != null) {
			try {
				//查询抽奖规则说明
				activityDesc = usersDao.getSysSettingHtmlInfo("luck_draw_activity_desc");
			} catch (Exception e) {
				activityDesc = "未获取到抽奖活动说明";
				logger.info("=============获取抽奖活动说明错误：", e);
			}
			List<Map<String, Object>> luckDrawList = luckDrawDao.queryLuckDrawList(paramsMap);
			Integer restLuckDrawTimes = 0;
			if(null == couponsLuckDraw){
				restLuckDrawTimes = 0;
			}else{
				restLuckDrawTimes = couponsLuckDraw.getDraw_rest_count();
			}
			rtnMap.put("restLuckDrawTimes",restLuckDrawTimes);
			rtnMap.put("activityDesc", activityDesc);
			rtnMap.put("list", luckDrawList);
			rtnMap.put("listSize", luckDrawList.size());
			rtnMap.put("rescode", Consts.SUCCESS_CODE);
			rtnMap.put("resmsg_cn", "查询成功！");
//		} else {
//			rtnMap.put("restLuckDrawTimes", 0);
//			rtnMap.put("activityDesc", activityDesc);
//			rtnMap.put("list", null);
//			rtnMap.put("listSize", 0);
//			rtnMap.put("rescode", Consts.SUCCESS_CODE);
//			rtnMap.put("resmsg_cn", "对不起，您现在还没有抽奖的机会，请投资之后再进行抽奖！");
//		}
		return rtnMap;
	}

	@Override
	public Map<String, String> isLuckDraw(String userId) throws Exception {
		Map<String, String> rtnMap = new HashMap<String, String>();

		Map<String, Object> paramsMap=new HashMap<String, Object>();
		paramsMap.put("userId", userId);
		CouponsLuckDraw couponsLuckDraw = couponsLuckDrawDao.queryCouponsLuckDrawByUserId(paramsMap);
		
		// 判断是否存在抽奖次数
		if (couponsLuckDraw != null) {
			// 判断是否还能继续抽奖
			Integer restDrawCount = couponsLuckDraw.getDraw_rest_count();
			logger.info("======================剩余抽奖次数为："+restDrawCount);
			if (restDrawCount > 0) {
				rtnMap.put("rescode", Consts.SUCCESS_CODE);
				rtnMap.put("resmsg", "");
				rtnMap.put("cid", String.valueOf(couponsLuckDraw.getId()));
				rtnMap.put("restLuckDrawTimes", String.valueOf(restDrawCount));
			} else {
				rtnMap.put("rescode", Consts.CHECK_CODE);
				rtnMap.put("resmsg", "");
				rtnMap.put("resmsg_cn", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				logger.info("======================对不起，你的抽奖次数用完了！");
			}
		} else {
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			logger.info("======================对不起，您没有抽奖资格，请先投资");
		}
		return rtnMap;
	}

	@Override
	public List<LuckDraw> getLuckDraw(Map<String, Object> paramsMap) throws Exception {
		List<LuckDraw> drawList = new ArrayList<LuckDraw>();
		List<Map<String, Object>> luckList = luckDrawDao.queryLuckDrawList(paramsMap);
		List<BigDecimal> orignalRates = new ArrayList<BigDecimal>(
				luckList.size());
		try {
			for (int i = 0; i < luckList.size(); i++) {
				Map<String, Object> luckMap = luckList.get(i);
				String winRate = luckMap.get("winRate")+"";
				orignalRates.add(new BigDecimal(winRate));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		int times = Integer.parseInt((String.valueOf(paramsMap.get("times"))));
		for (int i = 0; i < times; i++) {
			int index=lottery(orignalRates);
			Map<String, Object> resultMap=luckList.get(index);
			drawList.add(new LuckDraw(Long.valueOf(String.valueOf(resultMap.get("id"))), 
					String.valueOf(resultMap.get("awardName")), String.valueOf(resultMap.get("awardType")),
					String.valueOf(resultMap.get("params")), String.valueOf(resultMap.get("descName"))));
		}
		return drawList;
	}

	@Override
	@Transactional
	public Map<String, Object> setLuckDraw(Map<String,Object> paramsMap) throws Exception {
		Map<String, Object> returnMap = new HashMap<String,Object>();
		//生成相应奖品记录
		List<LuckDraw> luckDrawList = (List<LuckDraw>) paramsMap.get("luckDrawList");
		boolean f=false;
		for (int j = 0; j < luckDrawList.size(); j++) {
			LuckDraw luckDraw = luckDrawList.get(j);
			String awardType = luckDraw.getAwardType();
			String params = luckDraw.getParams();
			logger.info("=======（奖项种类(01-活期加息券,02-定期加息券,03-活期代金券,04-定期代金券，05-一元购,06-积分,99-其他）==========奖品类型为："+awardType);
			logger.info("=======奖项参数为："+params);
			//奖项种类(01-活期加息券,02-定期加息券,03-活期代金券,04-定期代金券，05-一元购,06-积分,99-其他）
			String[] items=null;
			if (params != null && !"".equals(params)
					&& params.lastIndexOf("|") != -1) {
				items = params.split("\\|");
			} else {
				items = new String[] {};
			}
			String userId = String.valueOf(paramsMap.get("userId"));
			if("01".equals(awardType)){
				f = insertRateRisesCoupons(userId, items);
			}else if("02".equals(awardType)){
				f= insertRateRisesCoupons(userId, items);
			}else if("03".equals(awardType)){
				f= insertVouchers(userId,items);
			}else if("04".equals(awardType)){
				f= insertVouchers(userId,items);
			}else if("05".equals(awardType)){
				Map<String,Object> addParam = new HashMap<String, Object>();
				addParam.put("userId", userId);
				addParam.put("mobile", paramsMap.get("mobile"));
				addParam.put("voucherId",1);
				addParam.put("source","4");//兑换券来源 1：K码激活赠送 2：发现购物赠送 3：新增定期赠送 4：活动赠送 5：积分兑换 0：其他
				Map<String,String> addResult = addShopVouchers(addParam);
				if(Consts.SUCCESS_CODE.equals(addResult.get("rescode"))){
					f = true;
				}
			}else if("06".equals(awardType)){//积分
				logger.info("=======积分奖项开始userId"+userId+"======");
				int amount = Integer.valueOf(items[0]);
				String mobile = String.valueOf(paramsMap.get("mobile"));
				pointService.luckyDrawPoint(userId,mobile,amount);
				f = true;
				logger.info("=======积分奖项结束userId"+userId+"======");
			}else if("99".equals(awardType)){
				f = true;
			}
			
		}
		if(f){
			//修改抽奖次数
			CouponsLuckDraw couponsLuckDraw = new CouponsLuckDraw();
			String cid = String.valueOf(paramsMap.get("cid"));
			couponsLuckDraw.setId(Long.valueOf(cid));
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("id", Long.valueOf(cid));
			map.put("times", paramsMap.get("times"));
			int count = couponsLuckDrawDao.updateCouponsDrawLuckInfoById(map);
			logger.info("=======更新修改抽奖次数条数："+count);
			if(count<=0){
				logger.info("=======更新抽奖次数失败");
				returnMap.put("rescode", Consts.ERROR_CODE);
				returnMap.put("resmsg", "");
				returnMap.put("resmsg_cn", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return returnMap;
			}
			
		}else{
			returnMap.put("rescode", Consts.ERROR_CODE);
			returnMap.put("resmsg", "");
			returnMap.put("resmsg_cn", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return returnMap;
		}
		returnMap.put("list", luckDrawList);
		returnMap.put("listSize", luckDrawList.size());
		returnMap.put("rescode", Consts.SUCCESS_CODE);
		returnMap.put("resmsg", "");
		returnMap.put("resmsg_cn", "抽奖成功！");
		return returnMap;
	}

	/**
	 * @Description: 特殊奖项记录
	 * @param @param userId
	 * @param @param items
	 * @param @return   
	 * @return boolean  
	 * @throws
	 * @author chenshufeng
	 * @date 2016-9-2
	 */
	private boolean insertSpecEvent(String userId, String awardId) {
		Map<String,Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userId", userId);
		paramMap.put("awardId", awardId);
		try {
			Integer count = luckDrawDao.insertSpecEvent(paramMap);
			if(count>0){
				return true;
			}
		} catch (Exception e) {
			logger.error("特殊奖项记录失败："+e);
			e.printStackTrace();
			return false;
		}
		return false;
	}
	
	/**
	 * @Description: 双旦奖项记录
	 * @param @param userId
	 * @param @param awardId
	 * @param @return   
	 * @return boolean  
	 * @throws
	 * @author chenshufeng
	 * @date 2016-12-8
	 */
	private boolean insertSDEvent(String userId, String awardId,String awardName) {
		Map<String,Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userId", userId);
		paramMap.put("awardId", awardId);
		paramMap.put("awardName", awardName);
		try {
			Integer count = luckDrawDao.insertSDEvent(paramMap);
			if(count>0){
				return true;
			}
		} catch (Exception e) {
			logger.error("特殊奖项记录失败：",e);
			e.printStackTrace();
			return false;
		}
		return false;
	}

	private boolean insertVouchers(String userId,String[] items) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date nowDate = sdf.parse(sdf.format(new Date()));
			Calendar cal = Calendar.getInstance();
			cal.setTime(nowDate);
			//代金券
			Map<String, Object> paramsMap=new HashMap<String, Object>();
			for (int j = 0; j < items.length; j++) {
				paramsMap.put("voucherId", items[j]);
				VouchersRule vouchersRule = userVouchersDao.queryVouchersRuleById(paramsMap);
				//代金券
				UserVouchers userVouchers = new UserVouchers();
				userVouchers.setUser_id(Long.valueOf(userId));
				userVouchers.setVoucher_type_id(Long.valueOf(items[j]));
				String validate = vouchersRule.getValidity_period()+"";
				if(StringUtil.isEmpty(validate)){
					validate = "0";
				}
				cal.add(Calendar.DATE, Integer.valueOf(validate));
				Date validityPeriodDate = cal.getTime();
				userVouchers.setStartdate(nowDate);
				userVouchers.setEnddate(validityPeriodDate);
				userVouchers.setVoucher_amount(vouchersRule.getVoucher_amount());
				userVouchers.setInvestment_amount(vouchersRule.getInvestment_amount());
				userVouchers.setSource("2");
				userVouchers.setGift_staff(userId);
				userVouchers.setCreate_time(new Date());
				userVouchers.setStatus("0");
				userVouchers.setCreate_per(userId);
				userVouchersDao.addUserVouchers(userVouchers);
			}
			return true;
		} catch (Exception e) {
			logger.error("=====================生成代金券错误："+e);
			return false;
		}
	}

	private boolean insertRateRisesCoupons(String userId, String[] items)
			 {
		try {
			int i=0;
			RateRisesCoupons rateRisesCoupons = new RateRisesCoupons();
			rateRisesCoupons.setUser_id(Long.valueOf(userId));
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date nowDate = sdf.parse(sdf.format(new Date()));
			Calendar cal = Calendar.getInstance();
			cal.setTime(nowDate);
			cal.add(Calendar.DATE, Integer.valueOf(items[i++])-1);
			rateRisesCoupons.setValidity_period(cal.getTime());
			
			//新增--start
			String productId=items[i++];
			int rateRisesDays=Integer.valueOf(items[i++]);
			//新增--end
			
			rateRisesCoupons.setProduct_id(productId);
			rateRisesCoupons.setRate_rises_days(rateRisesDays);
			rateRisesCoupons.setRate_rises(new BigDecimal(items[i++]));
			rateRisesCoupons.setGet_way("5");
			rateRisesCoupons.setStatus("0");
			rateRisesCoupons.setCreate_time(new Date());
			rateRisesCoupons.setMobile("");
			
			//新增--start
			//短期标加息天数 根据参数控制，0－表示不启用，1－表示启用短期标送加息券
    		String fhjxqControl=activityService.findParamValueByName("fhjxq_control");
            if("1".equals(fhjxqControl)&& "108".equals(productId)){
            	rateRisesCoupons.setRemanDays(rateRisesDays);
            }else{
            	rateRisesCoupons.setRemanDays(0);
            }
            //新增--end
            
			rateRisesCouponsDao.insertRateRisesCoupons(rateRisesCoupons);
			return true;
		} catch (Exception e) {
			logger.error("=====================生成加息券错误："+e);
			return false;
		}
	}

	/**
	 * 
	 * @Description: 抽奖算法
	 * @param @param orignalRates 原始的概率列表，保证顺序和实际物品对应
	 * @param @return   
	 * @return int 物品的索引 
	 * @throws
	 * @author chenshufeng
	 * @date 2016-8-3
	 */
	private int lottery(List<BigDecimal> orignalRates) {
		if (orignalRates == null || orignalRates.isEmpty()) {
			return -2;
		}

		int size = orignalRates.size();

		// 计算总概率，这样可以保证不一定总概率是1
		BigDecimal sumRate = new BigDecimal("0.0");
		for (BigDecimal rate : orignalRates) {
			sumRate = sumRate.add(rate);
		}
		//有库存的奖项的总概率为0
		if(sumRate.compareTo(BigDecimal.ZERO) == 0){
			return -3;
		}
		// 计算每个物品在总概率的基础下的概率情况
		List<BigDecimal> sortOrignalRates = new ArrayList<BigDecimal>(size);
		BigDecimal tempSumRate = new BigDecimal("0.0");
		for (BigDecimal rate : orignalRates) {
			tempSumRate = tempSumRate.add(rate);
			sortOrignalRates.add(tempSumRate.divide(sumRate,2,BigDecimal.ROUND_FLOOR));
		}

		// 根据区块值来获取抽取到的物品索引
		BigDecimal nextDouble = new BigDecimal(String.valueOf(Math.random()));
		sortOrignalRates.add(nextDouble);
		Collections.sort(sortOrignalRates);

		return sortOrignalRates.indexOf(nextDouble);
	}

	/**
	 * 特殊奖项列表
	 */
	@Override
	public Map<String, Object> getSpecGiftsList(Map<String, String> reqMap) throws Exception{
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		logger.info("=============参数：" + reqMap);
		// 查询抽奖设置信息
		Map<String,String> resMap = null;
		if(StringUtil.isNotEmpty(reqMap.get("userId"))){
			
			resMap = luckDrawDao.getSpecEvnTimes(Long.valueOf(reqMap.get("userId")));
		}
		String activityDesc = "";
		try {
			// 查询抽奖规则说明
			activityDesc = usersDao
					.getSysSettingHtmlInfo("spec_luck_draw_activity_desc");
		} catch (Exception e) {
			logger.info("=============特殊奖项活动说明错误：" + e);
		}
		//特殊奖项列表
		List<Map<String, Object>> giftsList = luckDrawDao.querySpecGiftsList();
		int times = 0;
		if(null != resMap){
			times = Integer.parseInt(resMap.get("MAXAMOUNT"))-Integer.parseInt(resMap.get("USEAMOUNT"));
		}
		rtnMap.put("restLuckDrawTimes", times<0?0:times);
		rtnMap.put("activityDesc", activityDesc);
		rtnMap.put("list", giftsList);
		rtnMap.put("listSize", giftsList.size());
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功！");
		return rtnMap;
	}

	/**
	 * 是否有抽奖资格
	 */
	@Override
	public Map<String, String> isExistLuckDrawTimes(String userId)
			throws Exception {
		Map<String, String> rtnMap = new HashMap<String, String>();
		// 查询抽奖设置信息
		Map<String,String> resMap = luckDrawDao.getSpecEvnTimes(Long.valueOf(userId));
		int times = 0;
		if(null != resMap){
			times = Integer.parseInt(resMap.get("MAXAMOUNT"))- Integer.parseInt(resMap.get("USEAMOUNT"));
		}
		// 判断是否存在抽奖次数
		logger.info("抽奖次数："+times);
		if (times <= 0 ) {
			// 判断是否还能继续抽奖
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return rtnMap;
		}
		rtnMap.put("restLuckDrawTimes", String.valueOf(times));
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg", "");
		rtnMap.put("resmsg_cn", "");
		return rtnMap;
	}

	/**
	 * 随机抽奖奖品
	 */
	@Override
	public int getRandomGiftNo() throws Exception {
		//变更抽奖列表
		List<Map<String, Object>> luckList = luckDrawDao.attendSpecGiftsList();
		if(null == luckList || luckList.size() == 0){
			logger.info("参与抽奖的奖品列表没有库存了！");
			return -1;
		}
		List<BigDecimal> orignalRates = new ArrayList<BigDecimal>(
				luckList.size());
		try {
			for (int i = 0; i < luckList.size(); i++) {
				Map<String, Object> luckMap = luckList.get(i);
				String winRate = luckMap.get("winRate")+"";
				orignalRates.add(new BigDecimal(winRate));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		int index=lottery(orignalRates);
		if (index < 0) {
			return index;
		}
		Map<String, Object> resultMap=luckList.get(index);
		Object o = resultMap.get("id");
		logger.info("随机抽奖奖品id："+o.toString());
		return Integer.valueOf(o.toString());
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	public Map<String, Object> sendGift(Map<String, String> paramsMap)
			throws Exception {
		Map<String, Object> returnMap = new HashMap<String,Object>();
		//生成相应奖品记录
		String giftId = paramsMap.get("giftId");
		LuckDraw luckDraw = luckDrawDao.getSpeEveDraw(Long.valueOf(giftId));
		String awardType = luckDraw.getAwardType();
		String params = luckDraw.getParams();
		String tipsMessage = luckDraw.getTipsMessage();
		logger.info("=======奖项种类(01-活期加息券,02-定期加息券,03-代金券,04-定期代金券,05-特殊奖,06-未中奖，99-其他)==========奖品类型为："+awardType);
		logger.info("=======奖项参数为："+params);
		//奖项种类(01-活期加息券,02-定期加息券,03-代金券,04-定期代金券,05-特殊奖,06-未中奖，99-其他)
		String[] items=null;
		if (params != null && !"".equals(params)
				&& params.lastIndexOf("|") != -1) {
			items = params.split("\\|");
		} else {
			items = new String[] {};
		}
		boolean f=false;
		String userId = paramsMap.get("userId");
		if("01".equals(awardType)){
			f = insertRateRisesCoupons(userId, items);
		}else if("02".equals(awardType)){
			f= insertRateRisesCoupons(userId, items);
		}else if("03".equals(awardType)){
			f= insertVouchers(userId,items);
		}else if("04".equals(awardType)){
			f= insertVouchers(userId,items);
		}else if("05".equals(awardType)){
			f= true;
		}else if("06".equals(awardType)){
			f= true;
		}else if("99".equals(awardType)){
			f = true;
		}
		if(f){
			int updateCount = luckDrawDao.updateSpecTimes(Long.valueOf(userId));
			if(updateCount<=0){
				logger.info("用户："+userId+"更新抽奖次数失败！");
				throw new RuntimeException("抽奖失败！");
			}
			boolean bool = insertSpecEvent(userId,giftId);
			if(bool == false){
				logger.info("用户："+userId+"记录抽奖结果失败！");
				throw new RuntimeException("抽奖失败！");
			}
			//库存更新
			try {
				updateStore(Long.valueOf(giftId));
			} catch (Exception e) {
				logger.error("更新特殊奖品库存发生了异常：",e);
			}
		}else{
			returnMap.put("rescode", Consts.ERROR_CODE);
			returnMap.put("resmsg", "");
			returnMap.put("resmsg_cn", "抽奖失败！");
			return returnMap;
		}
		String awardName = luckDraw.getAwardName().replaceAll("\\|","");
		logger.info(awardName);
		returnMap.put("id", luckDraw.getId());
		returnMap.put("awardName", awardName);
		returnMap.put("awardType", luckDraw.getAwardType());
		returnMap.put("tipsMessage", tipsMessage.replace("{1}", awardName));
		returnMap.put("rescode", Consts.SUCCESS_CODE);
		returnMap.put("resmsg", "");
		returnMap.put("resmsg_cn", "抽奖成功！");
		return returnMap;
	}
	/**
	 * 奖项列表(双旦)
	 */
	@Override
	public Map<String, Object> getSDGiftsList(Map<String, String> reqMap) throws Exception{
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		logger.info("=============参数：" + reqMap);
		// 查询抽奖设置信息
		Map<String,String> resMap = null;
		if(StringUtil.isNotEmpty(reqMap.get("userId"))){
			
			resMap = luckDrawDao.getSDTimes(Long.valueOf(reqMap.get("userId")));
		}
		String activityDesc = "";
		try {
			// 查询抽奖规则说明
			activityDesc = usersDao
					.getSysSettingHtmlInfo("sd_luck_draw_activity_desc");
		} catch (Exception e) {
			logger.info("=============双旦奖项活动说明错误：" ,e);
		}
		//特殊奖项列表
		List<Map<String, Object>> giftsList = luckDrawDao.querySDGiftsList();
		int times = 0;
		if(null != resMap){
			times = Integer.parseInt(resMap.get("MAXAMOUNT"))-Integer.parseInt(resMap.get("USEAMOUNT"));
		}
		rtnMap.put("restLuckDrawTimes", times<0?0:times);
		rtnMap.put("useAmount", Integer.parseInt(resMap.get("FIRSTAMOUNT")));//首次抽奖次数
		rtnMap.put("activityDesc", activityDesc);
		rtnMap.put("list", giftsList);
		rtnMap.put("listSize", giftsList.size());
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功！");
		return rtnMap;
	}
	
	/**
	 * 是否有抽奖资格(双旦)
	 */
	@Override
	public Map<String, String> isExistSDLuckDrawTimes(String userId,String drawFlag)
			throws Exception {
		Map<String, String> rtnMap = new HashMap<String, String>();
		// 查询抽奖设置信息
		Map<String,String> resMap = luckDrawDao.getSDTimes(Long.valueOf(userId));
		int times = 0;
		if(null != resMap){
			times = Integer.parseInt(resMap.get("MAXAMOUNT"))- Integer.parseInt(resMap.get("USEAMOUNT"));
			rtnMap.put("firstAmount", resMap.get("FIRSTAMOUNT"));
		}
		// 判断是否存在抽奖次数
		logger.info("抽奖次数："+times);
		if (times <= 0 && Integer.valueOf(drawFlag) != 0) {
			// 判断是否还能继续抽奖
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return rtnMap;
		}
		rtnMap.put("restLuckDrawTimes", String.valueOf(times));
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg", "");
		rtnMap.put("resmsg_cn", "");
		return rtnMap;
	}
	
	/**
	 * 随机抽奖奖品(双旦)
	 */
	@Override
	public int getRandomSDGiftNo(Map<String, Object> reqMap) throws Exception {
		//变更抽奖列表
		List<Map<String, Object>> luckList = luckDrawDao.attendSDGiftsList(reqMap);
		if(null == luckList || luckList.size() == 0){
			logger.info("参与抽奖的奖品列表没有库存了！");
			return -1;
		}
		List<BigDecimal> orignalRates = new ArrayList<BigDecimal>(
				luckList.size());
		try {
			for (int i = 0; i < luckList.size(); i++) {
				Map<String, Object> luckMap = luckList.get(i);
				String winRate = luckMap.get("winRate")+"";
				orignalRates.add(new BigDecimal(winRate));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		int index=lottery(orignalRates);
		if (index < 0) {
			return index;
		}
		Map<String, Object> resultMap=luckList.get(index);
		Object o = resultMap.get("id");
		logger.info("随机抽奖奖品id："+o.toString());
		return Integer.valueOf(o.toString());
	}
	
	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	public Map<String, Object> sendSDGift(Map<String, String> paramsMap)
			throws Exception {
		Map<String, Object> returnMap = new HashMap<String,Object>();
		//生成相应奖品记录
		String giftId = paramsMap.get("giftId");
		LuckDraw luckDraw = luckDrawDao.getSDDraw(Long.valueOf(giftId));
		String awardType = luckDraw.getAwardType();
		String params = luckDraw.getParams();
		String tipsMessage = luckDraw.getTipsMessage();
		logger.info("=======奖项种类(01-活期加息券,02-定期加息券,03-代金券,04-定期代金券,05-礼包,06-积分，99-其他)==========奖品类型为："+awardType);
		logger.info("=======奖项参数为："+params);
		//奖项种类(01-活期加息券,02-定期加息券,03-代金券,04-定期代金券,05-特殊奖,06-未中奖，99-其他)
		String[] items=null;
		if (params != null && !"".equals(params)
				&& params.lastIndexOf("|") != -1) {
			items = params.split("\\|");
		} else {
			items = new String[] {};
		}
		boolean f=false;
		String userId = paramsMap.get("userId");
		if("01".equals(awardType)){
			f = insertRateRisesCoupons(userId, items);
		}else if("02".equals(awardType)){
			f= insertRateRisesCoupons(userId, items);
		}else if("03".equals(awardType)){
			f= insertVouchers(userId,items);
		}else if("04".equals(awardType)){
			f= insertVouchers(userId,items);
		}else if("05".equals(awardType)){
//			Map<String,Object> addParam = new HashMap<String, Object>();
//			addParam.put("userId", userId);
//			addParam.put("mobile", paramsMap.get("mobile"));
//			addParam.put("voucherId",1);
//			addParam.put("source","4");//兑换券来源 1：K码激活赠送 2：发现购物赠送 3：新增定期赠送 4：活动赠送 5：积分兑换 0：其他
//			Map<String,String> addResult = addShopVouchers(addParam);
//			if(Consts.SUCCESS_CODE.equals(addResult.get("rescode"))){
//				f = true;
//			}
			//礼包
			logger.info("=======礼包奖项开始userId"+userId+"======");
			String giftOnOff=systemSettingDao.getSystemSettingValueByName("gift_on-off");
			logger.info("=======礼包奖项开关gift_on-off："+giftOnOff);
			if(StringUtil.isNotEmpty(giftOnOff) && "Y".equalsIgnoreCase(giftOnOff)){
				Map<String, String> welfareMap = new HashMap<String, String>();
				welfareMap.put("userId", userId);
				welfareMap.put("mobile", String.valueOf(paramsMap.get("mobile")));
				welfareMap.put("packageId", items[0]);
				Map<String,String> addResult = giftPackageService.giveWelFarePackage(welfareMap);
				if(!addResult.containsKey("error")){
					f = true;
				}
			}
			logger.info("=======礼包奖项结束userId"+userId+"======");
		}else if("06".equals(awardType)){//积分
			logger.info("=======积分奖项开始userId"+userId+"======");
			int amount = Integer.valueOf(items[0]);
			String mobile = String.valueOf(paramsMap.get("mobile"));
			pointService.luckyDrawPoint(userId,mobile,amount);
			f = true;
			logger.info("=======积分奖项结束userId"+userId+"======");
		}else if("99".equals(awardType)){
			f = true;
		}
		if(f){
			int updateCount = 0;
			if(Integer.valueOf(paramsMap.get("drawFlag")) == 0){
				updateCount = luckDrawDao.updateSDFirstTimes(Long.valueOf(userId));
			}else{
				updateCount = luckDrawDao.updateSDTimes(Long.valueOf(userId));
			}
			if(updateCount<=0){
				logger.info("用户："+userId+"更新抽奖次数失败！");
				throw new RuntimeException("抽奖失败！");
			}
			boolean bool = insertSDEvent(userId,giftId,tipsMessage);
			if(bool == false){
				logger.info("用户："+userId+"记录抽奖结果失败！");
				throw new RuntimeException("抽奖失败！");
			}
			//库存更新
			try {
				updateSDStore(Long.valueOf(giftId));
			} catch (Exception e) {
				logger.error("更新特殊奖品库存发生了异常：奖项ID为："+giftId,e);
			}
		}else{
			returnMap.put("rescode", Consts.ERROR_CODE);
			returnMap.put("resmsg", "");
			returnMap.put("resmsg_cn", "抽奖失败！");
			return returnMap;
		}
		String awardName = luckDraw.getAwardName().replaceAll("\\|","");
		logger.info(awardName);
		returnMap.put("id", luckDraw.getId());
		returnMap.put("awardName", awardName);
		returnMap.put("awardType", luckDraw.getAwardType());
		returnMap.put("tipsMessage", tipsMessage);
		returnMap.put("showImg", luckDraw.getShowImg());
		returnMap.put("rescode", Consts.SUCCESS_CODE);
		returnMap.put("resmsg", "");
		returnMap.put("resmsg_cn", "抽奖成功！");
		return returnMap;
	}

	private Integer updateStore(Long giftId) {
		return luckDrawDao.updateStore(giftId);
	}
	
	private Integer updateSDStore(Long giftId) {
		return luckDrawDao.updateSDStore(giftId);
	}
    /**
     * 送一元购券
     * @param paramsMap
     * @return
     * @throws Exception
     */
	public Map<String,String> addShopVouchers(Map<String, Object> paramsMap)
			throws Exception {
		String yygkg = systemSettingDao.getSystemSettingValueByName("yygkg");
		Map<String,String> rtnMap = new HashMap<String,String>();
		if(StringUtil.isEmpty(yygkg) || "0".equals(yygkg)){
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", "一元购关闭中！");
			return rtnMap;
		}
		String userId = paramsMap.get("userId") == null ? "" : paramsMap.get("userId").toString();
		String mobile = paramsMap.get("mobile") == null ? "" : paramsMap.get("mobile").toString();
		String voucherId = paramsMap.get("voucherId") == null ? "" : paramsMap.get("voucherId").toString();
		String source = paramsMap.get("source") == null ? "" : paramsMap.get("source").toString();
		String orderId = paramsMap.get("orderId") == null ? "" : paramsMap.get("orderId").toString();
		String giftStaff = paramsMap.get("giftStaff") == null ? "" : paramsMap.get("giftStaff").toString();
		if (StringUtil.isEmpty(userId) || StringUtil.isEmpty(voucherId) || StringUtil.isEmpty(source)) {
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", "该兑换券类型不存在！");
			return rtnMap;
		}
		Map<String,String> selSysVoucher = shopVouchersDao.selSysVoucher(paramsMap);
		if (null != selSysVoucher) {
			
			String validity = selSysVoucher.get("validity")==null?"":selSysVoucher.get("validity");
			String voucherType = selSysVoucher.get("voucherTypeId");
			String voucherAmount = selSysVoucher.get("voucherAmount");

			Calendar cal = Calendar.getInstance();
			Date nowDate = cal.getTime();
			if (!"".equals(validity)) {
				cal.add(Calendar.DATE, Integer.parseInt(validity)-1);
			} else {
				cal.add(Calendar.DATE, 29);
			}
			Date endTime = cal.getTime();
			ShopVouchers shopVour = new ShopVouchers(Long.parseLong(userId), mobile,
					Integer.parseInt(voucherId),voucherType,nowDate,endTime,
					orderId,new BigDecimal(voucherAmount),source,giftStaff);
			shopVouchersDao.addShopVoucher(shopVour);
		} else {
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", "该兑换券类型不存在！");
			return rtnMap;
		}
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg", "");
		rtnMap.put("resmsg_cn", "获取兑换券成功！");
		return rtnMap;
	}

	@Override
	public Map<String, Object> getSDLuckDrawResult(Map<String, Object> reqMap)
			throws Exception {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		int totalNum = luckDrawDao.getSDLuckDrawResultSize(reqMap);
		if(totalNum == 0){
			logger.info("userId"+reqMap.get("userId")+"没有中奖记录");
			rtnMap.put("totalNum", totalNum);
			rtnMap.put("list", new ArrayList());
			rtnMap.put("listSize", 0);
			rtnMap.put("rescode", Consts.SUCCESS_CODE);
			rtnMap.put("resmsg_cn", "查询成功！");
			return rtnMap;
		}
		List<Map<String, Object>> luckDrawList = luckDrawDao.getSDLuckDrawResult(reqMap);
		rtnMap.put("totalNum", totalNum);
		rtnMap.put("list", luckDrawList);
		rtnMap.put("listSize", luckDrawList.size());
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功！");
		return rtnMap;
	}
}
